package com.naiterui.common.jinshuju.service;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.naiterui.common.jinshuju.bean.JinshujuCallback;
import com.naiterui.common.jinshuju.bean.JinshujuInfo;
import com.naiterui.common.jinshuju.callback.router.CallbackRouter;
import com.naiterui.common.jinshuju.constants.JinshujuConstants;
import com.naiterui.common.jinshuju.event.JinshujuEvent;
import com.naiterui.common.jinshuju.exception.JinshujuException;
import com.naiterui.common.jinshuju.exception.JinshujuExceptionCodes;

import lombok.AllArgsConstructor;

/**
 *
 */
@Service
@AllArgsConstructor
public class JinshujuClientService {

    @Autowired
    private ApplicationEventPublisher eventPublisher;
    @Autowired
    private CallbackRouter callbackRouter;

    private static final Logger LOGGER = LoggerFactory.getLogger(JinshujuClientService.class);

    @Async
    public void handleCallback(String uid, JinshujuCallback jinshujuCallback) throws JinshujuException {

        if (null == jinshujuCallback || jinshujuCallback.getEntry().isEmpty() || StringUtils.isEmpty(uid)) {
            LOGGER.error("jinshuju callback saveForm error : form entry not complete ; json={}", jinshujuCallback);
            throw new JinshujuException(JinshujuExceptionCodes.CALLBACK_NOT_COMPLETE);
        }

        jinshujuCallback.setUid(uid);

        String openId = jinshujuCallback.getEntry().getOrDefault(JinshujuConstants.JINSHUJU_WX_OPENID_KEY, "").toString();
        String bizId = jinshujuCallback.getEntry().getOrDefault(JinshujuConstants.JINSHUJU_EXTRA_KEY, "").toString();
        String formId = jinshujuCallback.getForm();
        jinshujuCallback.setBizId(bizId);
        jinshujuCallback.setOpenId(openId);
        jinshujuCallback.setFormId(formId);

        JinshujuInfo jinshujuInfo = callbackRouter.route(jinshujuCallback);
        LOGGER.debug("jinshujuInfo {}", jinshujuInfo);
        eventPublisher.publishEvent(new JinshujuEvent(this, jinshujuInfo));
    }
}
